<template>
  <!-- 如果父组件的属性是直接应用到子组件的根标签上，可以不用设置props -->
  <input
    type="text"
    class="ipt"
    :value="value"
    @input="handleIput"
    :class="{
      success: state === 'success',
      error: state === 'error',
    }"
    @blur="blurFn"
  />
</template>

<script>
export default {
  data() {
    return {
      state: "",
    };
  },
  props: {
    rules: RegExp,
    value: String,
    msg: {
      type: String,
      default: "输入的数据不合法",
    },
  },
  methods: {
    handleIput(e) {
      // e.target触发事件的真实DOM节点
      // console.log(e.target.value);
      // 返回给父组件
      this.$emit("input", e.target.value);
    },
    blurFn(e) {
      const str = e.target.value.trim();
      if (this.rules.test(str)) {
        console.log(this.rules, str, "验证通过");
        this.state = "success";
      } else {
        console.log(this.rules, str, "验证失败", this.msg);
        this.$notify({ type: "warning", message: this.msg, duration: 1000 });
        this.state = "error";
      }
    },
  },
};
</script>

<style>
.ipt {
  width: 300px;
  height: 48px;
  border: none;
  outline: none;
  border-bottom: 3px solid #ccc;
  margin: 20px auto;
  display: block;
  background-color: transparent;
}
.success {
  border-bottom-color: green;
}
.error {
  border-bottom-color: red;
}
</style>